# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtGui import QPainter, QColor
from PySide6.QtWidgets import QHBoxLayout
from qfluentwidgets import CaptionLabel, isDarkTheme
from qfluentwidgets.multimedia import MediaPlayer
from qfluentwidgets.multimedia.media_play_bar import MediaPlayBarBase, MediaPlayBarButton


class CustomSimpleMediaPlayBar(MediaPlayBarBase):
    """ custom simple media play bar """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.hBoxLayout = QHBoxLayout(self)
        self.currentTimeLabel = CaptionLabel('0:00:00', self)
        self.remainTimeLabel = CaptionLabel('0:00:00', self)

        self.hBoxLayout.setContentsMargins(20, 4, 20, 4)
        self.hBoxLayout.setSpacing(6)
        self.hBoxLayout.addWidget(self.playButton, 0, Qt.AlignmentFlag.AlignLeft)
        self.hBoxLayout.addWidget(self.currentTimeLabel, 0, Qt.AlignmentFlag.AlignLeft)
        self.hBoxLayout.addWidget(self.progressSlider, 1)
        self.hBoxLayout.addWidget(self.remainTimeLabel, 0, Qt.AlignmentFlag.AlignRight)
        self.hBoxLayout.addWidget(self.volumeButton, 0)

        self.setFixedHeight(48)
        self.setMediaPlayer(MediaPlayer(self))

    def addButton(self, button: MediaPlayBarButton):
        """ add button to the right side of play bar """
        self.hBoxLayout.addWidget(button, 0)

    def _onPositionChanged(self, position: int):
        super()._onPositionChanged(position)
        self.currentTimeLabel.setText(self._formatTime(position))
        self.remainTimeLabel.setText(self._formatTime(self.player.duration() - position))

    def _formatTime(self, time: int):
        time = int(time / 1000)
        s = time % 60
        m = int(time / 60)
        h = int(time / 3600)
        if h > 0:
            return f'{h}:{m:02}:{s:02}'
        else:
            return f'{m}:{s:02}'

    def paintEvent(self, e):
        painter = QPainter(self)
        painter.setRenderHints(QPainter.RenderHint.Antialiasing)

        if isDarkTheme():
            painter.setBrush(QColor(46, 46, 46, 200))
            painter.setPen(QColor(0, 0, 0, 20))
        else:
            painter.setBrush(QColor(248, 248, 248, 200))
            painter.setPen(QColor(0, 0, 0, 20))

        r = self.height() // 2
        painter.drawRoundedRect(self.rect().adjusted(1, 1, -1, -1), r, r)
